package org.overmind.ieat.server.controllers.provider;

import org.overmind.ieat.server.model.ExceptionInfo;
import org.overmind.ieat.server.exceptions.provider.ProviderDeleteException;
import org.overmind.ieat.server.exceptions.provider.ProviderFindException;
import org.overmind.ieat.server.exceptions.provider.ProviderSaveException;
import org.overmind.ieat.server.exceptions.provider.ProviderUpdateException;
import org.overmind.ieat.server.factory.ExceptionInfoFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.servlet.http.HttpServletRequest;

/**
 * @author eugene.karanda
 */
@ControllerAdvice //TODO basePackage
public class ProviderExceptionProcessor {
    private static Logger logger = LoggerFactory.getLogger(ProviderExceptionProcessor.class);

    @Autowired
    private ExceptionInfoFactory exceptionInfoFactory;

    @ResponseBody
    @ExceptionHandler(ProviderFindException.class)
    @ResponseStatus(value = HttpStatus.NOT_FOUND)
    public ExceptionInfo findException(HttpServletRequest request, ProviderFindException exception) {
        return exceptionInfoFactory.createExceptionInfo(request, "exception.provider.find", exception.getRequiredId());
    }

    @ResponseBody
    @ExceptionHandler(ProviderSaveException.class)
    @ResponseStatus(value = HttpStatus.BAD_REQUEST)
    public ExceptionInfo saveException(HttpServletRequest request, ProviderSaveException exception) {
        return exceptionInfoFactory.createExceptionInfo(request, "exception.provider.save", exception.getProvider());
    }

    @ResponseBody
    @ExceptionHandler(ProviderUpdateException.class)
    @ResponseStatus(value = HttpStatus.BAD_REQUEST)
    public ExceptionInfo updateException(HttpServletRequest request, ProviderUpdateException exception) {
        return exceptionInfoFactory.createExceptionInfo(request, "exception.provider.update", exception.getUpdatedId(), exception.getProvider());
    }

    @ResponseBody
    @ExceptionHandler(ProviderDeleteException.class)
    @ResponseStatus(value = HttpStatus.NOT_FOUND)
    public ExceptionInfo deleteException(HttpServletRequest request, ProviderDeleteException exception) {
        return exceptionInfoFactory.createExceptionInfo(request, "exception.provider.delete", exception.getDeletedId());
    }
}
